package com.projectframe.base.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class WordReplaceText
{
    private static final int READ_LEN = 8192;
    
    private byte[] _fbyte;
    private int _filesize = 0;
    
    public WordReplaceText(String inpath) throws IOException
    {
        File f = new File(inpath); 
        FileInputStream fin = new FileInputStream(f);

        _fbyte = new byte[(int)f.length()];

        while(_filesize!=f.length())
        {
            int count = (int)(f.length() - _filesize);
            
            if( count>=READ_LEN)
                _filesize += fin.read(_fbyte, _filesize, READ_LEN);
            else
                _filesize += fin.read(_fbyte, _filesize, count);
        }
        
        fin.close();
    }

    public void save(String path) throws IOException
    {
        FileOutputStream fou = new FileOutputStream(path);
        fou.write(_fbyte, 0, _filesize);
        
        fou.flush();
        fou.close();
    }
    
    public byte[] getFileBytes()
    {
        return _fbyte;
    }
    
    public InputStream getInputStream()
    {
        return new ByteArrayInputStream(_fbyte, 0, _filesize);
    }
    
    public void replaceText(String oldstr, String newstr) throws IOException
    {
        if( newstr.length()>oldstr.length() )
        {
            throw new IOException("新字符串长度不能大于旧字符串长度！");
        }
        else if( newstr.length()<oldstr.length())
        {
            int count = oldstr.length() - newstr.length();
            
            for( int i=0; i<count; i++ )
                newstr += " ";
        }
        
        byte[] oldb = oldstr.getBytes("UTF-16LE"); //UTF-16LE
        byte[] newb = newstr.getBytes("UTF-16LE");
        
        for ( int i=0; i<_filesize; i++ )
        {
            if( oldb[0]==_fbyte[i] )
            {
                if( comparisonByte(oldb, 0, _fbyte, i) )
                    i += copeByte(newb, _fbyte, i);
            }
        }
    }
    
    private boolean comparisonByte(byte[] oldb, int o_offset, byte[] fileb, int f_offset)
    {
        if( fileb.length-f_offset<oldb.length )
            return false;
        
        for( int i=0; i<oldb.length; i++ )
        {
            if( oldb[o_offset+i]!=fileb[f_offset+i] )
                return false;
        }
        
        return true;
    }
    
    private int copeByte(byte[] newb, byte[] fileb, int f_offset)
    {
        for( int i=0; i<newb.length; i++ )
            fileb[f_offset+i] = newb[i];
        
        return newb.length-1;
    }
}
